package com.wswy.wzcx.ui.car.choose

import android.app.Activity
import android.arch.lifecycle.Observer
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import com.che.libcommon.ui.VOMessage
import com.che.libcommon.ui.loading.ILoadingView
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersDecoration
import com.wswy.wzcx.R
import com.wswy.wzcx.api.Api
import com.wswy.wzcx.model.ICity
import com.wswy.wzcx.model.WZCity
import com.wswy.wzcx.model.car.JZGCity
import com.wswy.wzcx.model.resp.ProvinceData
import com.wswy.wzcx.module.base.CBaseLoadingActivity
import com.wswy.wzcx.module.base.Resource
import com.wswy.wzcx.ui.Constants
import com.wswy.wzcx.widget.SideBar
import kotlinx.android.synthetic.main.activity_choose_city.*
import java.util.*

class ChooseCityActivity : CBaseLoadingActivity() {

    companion object {

        /**
         * 精真估 城市
         */
        fun startCityJZG(context: Context):Intent = Intent(context,ChooseCityActivity::class.java).apply {
            putExtra("type",ChooseCityAdapter.HOT_TYPE_JZG)
        }

        /**
         * 本地城市
         */
        fun startCityWZ(context: Context):Intent = Intent(context,ChooseCityActivity::class.java).apply {
            putExtra("type",ChooseCityAdapter.HOT_TYPE_WZ)
        }

        /**
         * 选择城市 省市
         */
        fun startPCityChoose(context: Context):Intent = Intent(context,ChooseCityActivity::class.java).apply {
            putExtra("type",ChooseCityAdapter.SHOW_TYPE_P_CITY)
        }

    }

    private lateinit var chooseCityViewModel: ChooseCityViewModel


    private val indexed = IntArray(27) {-1}


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_choose_city)

        val type = intent?.getIntExtra("type",ChooseCityAdapter.HOT_TYPE_WZ)?:ChooseCityAdapter.HOT_TYPE_WZ;

        setAppTitle("选择城市")

        chooseCityViewModel = provideViewModel(ChooseCityViewModel::class.java)

        showLoading(true)



        val adapter = ChooseCityAdapter(type)
        val layoutManager = LinearLayoutManager(this)

        recycler_view.layoutManager = layoutManager




        if (type == ChooseCityAdapter.SHOW_TYPE_P_CITY){
            //省市选择
            adapter.cityClickListener = {

                if (isValidCity(it)) {
                    setResult(Activity.RESULT_OK, Intent().apply {
                        putExtra(Constants.EXTRA_DATA_CHOOSE_CITY, it)
                    })
                    finish()
                }
            }
        }else{
            //正常城市列表
            adapter.setOnItemClickListener { _, _, city ->
                if (isValidCity(city)) {
                    setResult(Activity.RESULT_OK, Intent().apply {
                        putExtra(Constants.EXTRA_DATA_CHOOSE_CITY, city)
                    })
                    finish()
                }
            }
        }

        adapter.topHotClickListener = {

            if (isValidCity(it)){
                setResult(Activity.RESULT_OK, Intent().apply {

                    putExtra(Constants.EXTRA_DATA_CHOOSE_CITY,it)
                })
                finish()
            }
        }

        recycler_view.adapter = adapter

        recycler_view.addItemDecoration(StickyRecyclerHeadersDecoration(adapter))


        when(type){

            ChooseCityAdapter.HOT_TYPE_WZ -> {
                chooseCityViewModel.loadWZCity()
                val observer = Observer<Resource<Map<String, MutableList<WZCity>>>> {
                    it?.run {

                        if (inLoading()) {
                            showLoading(true)
                        } else if (isOk()) {
                            showData()

                            var len = 0
                            TreeMap<String, List<ICity>>(it.data).apply {
                                put("@", arrayListOf(ICity.HOT_PLACEHOLDER))
                            }.flatMapTo(mutableListOf()) {
                                indexed[it.key[0] - '@'] = len
                                len += it.value.size
                                it.value
                            }.run {

                                adapter.setNewData(this)
                                adapter.notifyDataSetChanged()
                            }

                        } else {
                            showError(VOMessage())
                        }
                    }
                }
                chooseCityViewModel.getWZCityLiveData().observe(this, observer)
            }

            ChooseCityAdapter.SHOW_TYPE_P_CITY -> {
                //选省市
                chooseCityViewModel.loadWZProvCity()
                val observer = Observer<Resource<Map<String, MutableList<ProvinceData>>>> {
                    it?.run {

                        if (inLoading()) {
                            showLoading(true)
                        } else if (isOk()) {
                            showData()

                            var len = 0
                            TreeMap<String, List<ICity>>(it.data).apply {
                                put("@", arrayListOf(ICity.HOT_PLACEHOLDER))
                            }.flatMapTo(mutableListOf()) {
                                indexed[it.key[0] - '@'] = len
                                len += it.value.size
                                it.value
                            }.run {

                                adapter.setNewData(this)
                                adapter.notifyDataSetChanged()
                            }

                        } else {
                            showError(VOMessage())
                        }
                    }
                }
                chooseCityViewModel.getProvCityLiveData().observe(this, observer)

            }

            ChooseCityAdapter.HOT_TYPE_JZG -> {
                chooseCityViewModel.loadJZGCity()
                chooseCityViewModel.getJZGCityLiveData().observe(this, Observer {
                    it?.run {

                        if (inLoading()) {
                            showLoading(true)
                        } else if (isOk()) {
                            showData()

                            var len = 0
                            TreeMap<String, List<ICity>>(it.data).apply {
                                put("@", arrayListOf(ICity.HOT_PLACEHOLDER))
                            }.flatMapTo(mutableListOf()) {
                                indexed[it.key[0] - '@'] = len
                                len += it.value.size
                                it.value
                            }.run {

                                adapter.setNewData(this)
                                adapter.notifyDataSetChanged()
                            }

                        } else {
                            showError(VOMessage())
                        }
                    }


                })
            }
        }







        indexBar.setOnChooseLetterChangedListener(object :SideBar.OnChooseLetterChangedListener{
            override fun onChooseLetter(s: String?) {

                s?.get(0)?.run {

                    if (Character.isLetter(this)){

                        val pos = indexed[this - 'A']
                        if (pos >= 0) {
                            layoutManager.scrollToPositionWithOffset(pos, 0)
                        }

                    }else if (this == '#'){
                        layoutManager.scrollToPositionWithOffset(0, 0)
                    }

                }



            }

            override fun onNoChooseLetter() {
            }

        })



    }


    private fun isValidCity(city:ICity?) : Boolean = city?.headerId?:0 != '@'.toLong()

    override fun getConfigure(): ILoadingView.LoadingConfigure? {
        return null
    }

    override fun getRootLayoutViewId(): Int = R.id.layout_root

    override fun getLoadingFrameId(): Int = R.id.fl_content

}